const nodeSchedule  = require('node-schedule');
const log4js     = require('../utils/logUtils');
const deviceCache = require("../db/deviceCache");
const logger     = log4js.getLogger('service');
const upwardsModel = require("../model/upwards");
const registerHandler = require("../sip/client/handler/registerHandler");

const TAG = "[计划任务]";
let mySchedule;

/**
 * 计划任务，向上注册
 */
let Register28181={
    /**
     * 开启定时器
     */
    start:function(){
        // 启用向上级连
        // 从数据库读取级连信息
        upwardsModel.load().then((upwards)=>{
            upwards.forEach(async (upward)=>{
                if(upward.in_use) {
                    // 向上级连，目前只支持一个上级
                    deviceCache.localUri = "sip:" + upward.self_account + "@" + upward.upper_realm;
                    logger.info(TAG, '[向上级连] 每10分钟运行一次', upward, deviceCache.localUri);

                    await registerHandler.REGISTER_ONCE(null, function (ret) {
                        logger.info(TAG, "向上级连成功", ret);
                    });
                }
            });
        });
    },
    startSchedule:function(){
        const that = this;
        // 每10分钟运行一次
        const interval = '0 */10 * * * *';
        that.start();
        mySchedule = nodeSchedule.scheduleJob(interval,function(){
            that.start();
        });
    },
    /**
     * 取消定时器
     */
    stop:function(){
        if(mySchedule){
            mySchedule.cancel();
        }
    }
};

module.exports=Register28181;
